package chpt09;

import java.util.concurrent.TimeUnit;

public class SleepTest {
	public static void main(String[] args) {
		System.out.println("Main begin");
		sleepTest();
		System.out.println("Main End");
	}
	public static void sleepTest() {
		Thread t1 = new Thread(() -> {
			Thread curThread = Thread.currentThread();
			curThread.setName("T1");
			String name = curThread.getName();
			System.out.println("2. T1 " + curThread.getState()); // 2. T1 RUNNABLE
			for (int i = 0; i < 3; i++) {
				System.out.println(name + " " + i);
				try {
					Thread.sleep(500);					
					// throw new RuntimeException();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println("T1 end");
		}); // t1 end
		System.out.println("1. T1 " + t1.getState()); // 1. T1 NEW
		
		Thread t2 = new Thread(() -> {
			Thread curThread = Thread.currentThread();
			curThread.setName("T2");
			String name = Thread.currentThread().getName();
			for (int i = 0; i < 5; i++) {
				System.out.println(name + " " + i);
				try {
					TimeUnit.SECONDS.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}); // t2 end 
		t1.start();	
		t2.start();
		try {
			Thread.sleep(2000); // 主线程休眠，尽量保证t1已经运行完
			// TimeUnit.SECONDS.sleep(2); // 也可使用该方法休眠，
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("3. T1 " + t1.getState()); // 3. T1 TERMINATED
	}
}
